﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Steve.UI.Administration.Models;
using Microsoft.Web.Mvc.AspNet4;

namespace Steve.UI.Administration
{
    public static class ModelMetadataExtensions
    {
        public static string GetGroupName(this ModelMetadata metadata)
        {
            if (metadata == null) throw new ArgumentNullException("metadata");

            if (metadata.AdditionalValues.ContainsKey("GroupName"))
            {
                return (string)metadata.AdditionalValues["GroupName"];
            }

            return null;
        }
    }

    namespace DataAnnotations
    {
        public class AdministrationModelMetadataProvider : DataAnnotations4ModelMetadataProvider
        {
            protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
            {
                var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

                var category = attributes.OfType<DisplayAttribute>().FirstOrDefault();
                if (category != null) result.AdditionalValues["GroupName"] = category.GetGroupName();

                var show = attributes.OfType<ShowAttribute>().FirstOrDefault();

                if (show != null)
                {
                    result.ShowForDisplay = show.ForDisplay;
                    result.ShowForEdit = show.ForEdit;
                }

                return result;
            }
        }
    }
}